package com.coder.rental.controller;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.security.CustomerAuthenticationException;
import com.coder.rental.service.IUserService;
import com.coder.rental.utils.JwtUtil;
import com.coder.rental.utils.RedisUtil;
import com.coder.rental.utils.Result;
import com.coder.rental.utils.RouteTreeUtil;
import com.coder.rental.vo.RouteVo;
import com.coder.rental.vo.TokenVo;
import com.coder.rental.vo.UserInfoVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/rental/auth")
public class AuthController {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IUserService userService;

    // 刷新token
    @PostMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request){
        // 获取token
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            token = request.getParameter("token");
        }
        // 从上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        String username = JwtUtil.parseToken(token).getClaim("username").toString();
        String newtoken = "";
        if(StrUtil.equals(username,userDetails.getUsername())){
            // 生成新的token
            Map<String,Object> map=new HashMap<>();
            map.put("username",userDetails.getUsername());
            newtoken= JwtUtil.createToken(map);
        }
        else {
            throw new CustomerAuthenticationException("token数据异常");
        }
        // 获取本次token过期时间
        NumberWithFormat claim = (NumberWithFormat) JwtUtil.parseToken(newtoken).getClaim(JWTPayload.EXPIRES_AT);
        DateTime dateTime = (DateTime) claim.convert(DateTime.class,claim);
        long expireTime= dateTime.getTime();
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(newtoken).setExpireTime(expireTime);
        // 清除原有token
        redisUtil.del("token:"+token);

        long nowTime = DateTime.now().getTime();
        String newTokenKey="token:"+newtoken;
        redisUtil.set(newTokenKey,newtoken,(expireTime-nowTime)/1000);
        return Result.success(tokenVo).setMessage("刷新token成功！");
    }

    // 获取信息
    @GetMapping("/getInfo")
    public Result getUserInfo(){
        // 用户信息从哪来？securityContextHolder上下文获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication == null){
            return Result.fail().setMessage("认证信息为空");
        }
        User user = (User) authentication.getPrincipal();
        /*Object[] array = user.getPermissionList().stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode).toArray();*/

        /*List<String> list = userService.selectRoleByUserId(user.getId());
        Object[] array = list.toArray();*/
        List<Permission> permissionList = user.getPermissionList();
        Object[] array = permissionList.stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .toArray();
        // 创建并填充用户信息视图对象
        UserInfoVo userInfoVo = new UserInfoVo(user.getId(), user.getUsername(),
                user.getAvatar(), user.getNickname(),array);
        return Result.success(userInfoVo).setMessage("获取用户信息成功！");
    }

    @GetMapping("/menuList")
    public Result getMenuList(){
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication == null){
            return Result.fail().setMessage("认证信息为空");
        }
        User user = (User) authentication.getPrincipal();
        // 获取用户的权限列表
        List<Permission> permissionList = user.getPermissionList();
        // 获取用户的权限列表
        // 将permission_type2的按钮移除，不要生成对应的菜单
        permissionList.removeIf(permission -> Objects.equals(permission.getPermissionType(),2));
        List<RouteVo> routeVos = RouteTreeUtil.buildRouteTree(permissionList, 0);
        return Result.success(routeVos).setMessage("获取用户菜单成功！");
    }

    // 登出
    /**
     * 逻辑就是：删除redis中的token，然后调用SpringSecurity的登出方法(SecurityContextLogoutHandler类)
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response){
        String token=request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            token=request.getParameter("token");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null){
            //用户一旦登出系统，则清除redis中的token
            redisUtil.del("token:"+token);
            SecurityContextLogoutHandler handler = new SecurityContextLogoutHandler();
            handler.logout(request,response,authentication);
            return Result.success().setMessage("登出成功");
        }
        return Result.fail().setMessage("登出失败");
    }

    //
}
